import asyncio
from alist import AList, AListUser
import os
from pathlib import Path
from utils.YamlLoader import YamlConfigLoader
from utils.PathConverter import AbsolutePathConverter
import traceback

# 初始化加载器 (自动合并多个配置文件)
config_loader = YamlConfigLoader([
    "configs/alist.yml"
])

# 初始化 AList3SDK 客户端
user = AListUser(config_loader.get("alist.username",None,str), config_loader.get("alist.password",None,str))  # 用户名和密码
client = AList(config_loader.get("alist.url",None,str))  # 服务器 URL

async def upload_and_delete(local_file_path: str, remote_dir_path: str , cover:bool=True, delete:bool=False) -> bool:
    """
    将本地文件上传至Alist指定路径，上传成功后删除本地文件
    
    :param local_file_path: 本地待上传文件的完整路径
    :param remote_dir_path: Alist存储的目录路径
    :return: 操作是否成功
    """
    local_file_path = AbsolutePathConverter.safe_convert(local_file_path)
    print(local_file_path)
    # 初始化Alist客户端（需替换为你的服务器配置）
    ready = await client.login(user) 

    try:
        print(f"正在创建文件路径{remote_dir_path}")
        ALFS = await client.open(remote_dir_path)
        if ALFS is not None:
            print("文件路径已经存在")
        else:
            # 自动创建远程目录
            su = await client.mkdir(remote_dir_path)
            if not su:
                print(f"创建文件路径{remote_dir_path}失败")
                return False
            print("创建成功")
        
        print("正在上传文件。。。")
        os.path.basename(local_file_path)
        file_path = Path(remote_dir_path) / Path(local_file_path).name
        ALFS = await client.open(file_path)
        if ALFS is not None:
            print("文件已经存在")
            if cover:
                print("删除云端文件")
                if await client.remove(file_path):
                    print("删除成功")
                else:
                    print("删除失败")
                    return False
            else:
                return True
        print(f"正在上传文件 {Path(local_file_path).name}")
        # 上传文件
        su = await client.upload(file_path,local_file_path)
        if su and delete:
            # 删除本地文件
            os.remove(local_file_path)
            print(f"文件 {Path(local_file_path).name} 已成功上传并删除")
            return True
        elif su:
            print(f"文件 {Path(local_file_path).name} 已成功上传")
            return True
        print("上传失败")
        return False
        
    except Exception as e:
        print(f"操作失败: {str(e)}")
        traceback.print_exc()
        return False

asyncio.run(upload_and_delete("./test.txt","/123/test/",True,False))